package org.aliwo.concurrency;

import java.util.concurrent.Semaphore;

/**
 * Semaphore(信号量) 学习
 * 控制并发数
 * 使用场景: 接口限流
 */
public class SemaphoreTest {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(8);

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + ": 获取信号量");
                    Thread.sleep(5000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println(Thread.currentThread().getName() + ": 释放信号量");
                    semaphore.release();
                }
            }, "线程" + i).start();
        }

    }
}
